import {
  getAllAwardRecords,
} from '/common/api';

Component({
  data: {
    scrollTop: 0,
    userList: [],
  },

  props: {
    hide: true,
  },

  didMount() {
    this.showAwardRecords();
  },

  didUpdate(prevProps) {
    const { hide: prevHide } = prevProps;
    const { hide: nowHide } = this.props;
    if (!prevHide && nowHide) {
      // 当页面隐藏 onHide
      if (this.timer) clearInterval(this.timer);
      if (this.timerScroll) clearInterval(this.timerScroll);
      this.setData({
        scrollTop: 0,
      })
    } else if (prevHide && !nowHide) {
      // 当页面显示 onShow
      this.showAwardRecords();
    }
  },

  didUnmount() {
    if (this.timer) clearInterval(this.timer);
    if (this.timerScroll) clearInterval(this.timerScroll);
  },

  methods: {
    // 展示中奖名单
    showAwardRecords() {
      const $this = this;
      this.renderAwardRecords();
      this.timer = setInterval(() => {
        $this.renderAwardRecords();
      }, 20000);
    },
  
    renderAwardRecords() {
      const $this = this;
      getAllAwardRecords(50)
        .then((res) => {
          const { data } = res;
          if (data.success) {
            $this.setData({
              userList: data.data.list,
            }, () => {
              if (data.data.list.length > 5) {
                $this.handleScrollWrapper();
              }
            });
          } else {
            my.showToast({
              type: 'fail',
              content: data.message,
            });
          }
        }).catch((err) => {
          console.log(err);
        });
    },
  
    // 中奖名单循环滚动
    handleScrollWrapper() {
      const $this = this;
      my.createSelectorQuery()
        .select('#scroll')
        .boundingClientRect()
        .exec((res) => {
          const { height } = res[0];
          const scrollScope = parseInt(height / 2);
          let initTop = 0;
          if ($this.timerScroll) clearInterval($this.timerScroll);
          $this.timerScroll = setInterval(() => {
            $this.setData({
              scrollTop: initTop -= 2,
            });
            if (-initTop >= scrollScope) {
              initTop = 0;
            }
          }, 80);
        });
    },
  },
});
